﻿using DTO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;

namespace Api.Filter
{
    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                var validationErrors = modelState.Keys
                    .SelectMany(key => modelState[key].Errors.Select(x => x.ErrorMessage));
                context.Result = new JsonResult(Result.Failed(500, $"参数错误:{string.Join("; ", validationErrors)}"), new JsonSerializerSettings()
                {
                    ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                }); new ObjectResult(validationErrors);
            }
        }
    }
}